<template>
  <!-- 知识类型管理 -->
  <div class="knowledgeType">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
          <el-form-item prop="knowledgeCode" label="知识编号">
            <el-input v-model="formData.knowledgeCode" placeholder="请输入知识编号" clearable />
          </el-form-item>
          <el-form-item prop="type" label="知识类型名称">
            <SearchSelectPicker
              url="/call-center/api/v1/knowledgeType/page"
              placeholder="请选择类型名称"
              lable-name="typeName"
              :value.sync="formData.type"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="title" label="知识标题">
            <el-input v-model="formData.title" placeholder="请输入知识标题" clearable />
          </el-form-item>
          <el-form-item prop="state" label="审核状态">
            <el-select v-model="formData.state" clearable>
              <el-option label="未审核" :value="1" />
              <el-option label="审核通过" :value="2" />
              <el-option label="审核不通过" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item prop="createrName" label="创建人">
            <el-input v-model="formData.createrName" placeholder="请输入创建人" clearable />
          </el-form-item>
          <el-form-item prop="isAuditRequired" label="是否需要审核">
            <el-select v-model="formData.isAuditRequired" clearable>
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="createTime" :span="7" label="创建时间">
            <el-date-picker
              v-model="formData.createTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
            />
          </el-form-item>
          <el-form-item :span="5">
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="add">新增</Button>
        <Button type="primary" @click="update">编辑</Button>
        <Button type="primary" @click="downloadFile">模板下载</Button>
        <el-upload
          class="upload-demo"
          :headers="headers"
          action="/call-center/api/v1/knowledgeBase/insertBatch"
          :on-success="onSuccess"
          :on-error="()=>{loading = false}"
          :before-upload="beforeUpload"
        >
          <Button type="primary" :loading="loading">批量导入</Button>
        </el-upload>
        <Button type="danger" @click="delet">删除</Button>
        <Button type="primary" @click="toExamine">审核</Button>
      </div>
      <table-box
        ref="table"
        no-request
        :selected-arry.sync="selectedArry"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        @selection-change="selectionChange"
      ></table-box>
      <AddEdit ref="addEdit" :dailog-type="dailogType" @confrim="refreshList" />
      <Examine ref="examine" @confrim="refreshList" />
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import AddEdit from './child/AddEdit'
import Examine from './child/Examine'
import { contentDeleteBatch, contentDetail, templateDownload } from '@/api/knowledgeBase'
import { getToken } from '@/utils/auth'
import { filtersRaw, addOneDay } from '@/utils'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { downFileByStream } from '@/utils/index'
export default {
  name: 'KnowledgeCotntManage',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    AddEdit,
    Examine,
    SearchSelectPicker
  },
  data() {
    return {
      loading: false,
      dailogType: '0',
      headers: {},
      formData: {
        auditorType: 'needAuditor',
        knowledgeCode: '',
        typeName: '',
        type: '',
        title: '',
        state: '',
        isAuditRequired: '',
        createBy: '',
        createTime: []
      },
      formRules: {},
      otherFilters: [],
      user: this.$store.getters.user,
      selectedArry: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/knowledgeBase/page',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [
          {
            prop: 'knowledgeCode',
            label: '知识编号',
            minWidth: 100
          },
          {
            prop: 'typeName',
            label: '知识类型名称',
            minWidth: 120
          },
          {
            prop: 'title',
            label: '知识标题',
            minWidth: 100,
            className: 'table-click-text',
            isButton: true,
            clickFun: row => {
              this.detail(row)
            }
          },
          {
            prop: 'organizationName',
            label: '使用业务组',
            minWidth: 140
          },
          {
            prop: 'createrName',
            label: '创建人',
            minWidth: 100
          },
          {
            prop: 'createTime',
            label: '创建时间',
            formatData: val => {
              return val.createTime ? val.createTime.substring(0, 19) : ''
            },
            minWidth: 100
          },
          {
            prop: 'isAuditRequired',
            label: '是否需要审核',
            formatData: val => {
              return val.isAuditRequired === 1 ? '是' : '否'
            },
            minWidth: 120
          },
          {
            prop: 'auditorName',
            label: '审核人',
            minWidth: 100
          },
          {
            prop: 'state',
            label: '审核状态',
            formatData: val => {
              return val.isAuditRequired === 0
                ? ''
                : val.state === 1
                  ? '未审核'
                  : val.state === 2
                    ? '审核通过'
                    : val.state === 3
                      ? '审核不通过'
                      : ''
            },
            minWidth: 100
          },
          {
            prop: 'auditRemarks',
            label: '审核备注',
            minWidth: 120
          },
          {
            prop: 'auditTime',
            label: '审核时间',
            formatData: val => {
              return val.auditTime
                ? val.auditTime.substring(0, 19)
                : ''
            },
            minWidth: 120
          },
          {
            prop: 'lastUpdateName',
            label: '最近更新人',
            minWidth: 110
          },
          {
            prop: 'lastUpdateTime',
            label: '最近更新时间',
            formatData: val => {
              return val.lastUpdateTime
                ? val.lastUpdateTime.substring(0, 19)
                : ''
            },
            minWidth: 120
          }
        ]
      },
      pickerOptions: {
        disabledDate(date) {
          return date > new Date()
        }
      }
    }
  },
  computed: {
    auditDisabled() {
      // 是否禁用审核按钮
      if (this.selectedArry.length !== 1) {
        return true
      } else {
        const obj = this.selectedArry[0]
        // 还需要加上当前账号是否为审核人判断
        if (
          obj.isAuditRequired === 1 &&
          obj.state === 1 &&
          this.$self(obj.auditor)
        ) {
          return false
        }
        return true
      }
    }
  },
  created() {
    this.headers['token'] = getToken()
    this.headers['Authorization'] = `Bearer ${getToken()}`
  },
  methods: {
    // 根据条件查询
    queryHandle() {
      const list = []
      for (const i in this.formData) {
        if (i === 'createTime') {
          if (this.formData[i] && this.formData[i].length) {
            list.push(filtersRaw(i, this.formData[i][0], '>='))
            list.push(filtersRaw(i, addOneDay(this.formData[i][1]), '<='))
          }
        } else {
          if (this.formData[i] || this.formData[i] === 0) {
            if (i === 'id' || i === 'isAuditRequired') {
              list.push(filtersRaw(i, this.formData[i], '='))
            } else {
              list.push(filtersRaw(i, this.formData[i], 'like'))
            }
          }
        }
      }
      this.otherFilters = list
      // return
      this.$nextTick(() => {
        this.$refs.table.initTableData()
      })
    },
    // 新增按钮
    add() {
      this.tempData = {}
      this.dailogType = '0'
      this.$refs.addEdit.openDailog()
    },
    // 修改按钮
    update() {
      this.dailogType = '1'
      if (this.selectedArry.length === 0) {
        this.$message({
          message: '请选择需要编辑的知识',
          type: 'info'
        })
        return
      }
      if (!this.canControl(this.selectedArry[0])) {
        this.$message({
          message: '您没有权限操作该知识',
          type: 'info'
        })
        return
      }
      contentDetail(this.selectedArry[0].id).then(res => {
        if (res.success === 1) {
          this.$refs.addEdit.openDailog(res.data)
        }
      })
    },
    canControl(data) {
      // 判断是否具有操作权限
      const isAuditRequired = data.isAuditRequired
      const organizationCode = data.organizationCode ? data.organizationCode.split(',') : []
      const auditor = data.auditor
      const createBy = data.createBy
      let bol = false // 能否操作
      if (isAuditRequired === 1) {
        if (this.$isAccount(createBy) || this.$isAccount(auditor)) {
          bol = true
        }
        // 3.原需审核的知识类型名称，只有创建人和审核人可以修改，新修改后仍需审核，即由审核人审核，
        // 如不需审核，修改后即可发布。 当前登录用户 ?= createBy, auditor
      } else if (isAuditRequired === 0) {
        organizationCode.forEach(e => {
          if (this.$inGroup(e)) {
            bol = true
            return
          }
        })
        // 1.原不需要审核的知识类型名称，可使用的角色都可以修改；
        // 2.原不需要审核的知识类型名称，修改后如果还是不需审核即可发布，如需审核，则审核后发布；
        // 当前登录用户 角色是否在 知识库浏览权限中
      }
      return bol
    },
    beforeUpload() {
      this.loading = true
    },
    // 上传成功，返回列表数据
    onSuccess(res) {
      this.loading = false
      if (res.success === 1) {
        this.$message.success('数据导入成功!')
      } else {
        this.$notify.error({
          title: '导入错误提示',
          message: res.msg + '!请修改后重新导入',
          duration: 0
        })
      }
    },
    // 执行删除
    delet() {
      if (this.selectedArry === 0) {
        this.$message({
          message: '请选择需要删除的知识',
          type: 'info'
        })
        return
      }
      if (!this.canControl(this.selectedArry[0])) {
        this.$message({
          message: '您没有权限删除该知识',
          type: 'info'
        })
        return
      }
      return this.$msgbox({
        type: 'warning',
        title: '确认删除',
        showCancelButton: true,
        message: '确定删除选中内容？'
      })
        .then(() => {
          var ids = this.selectedArry.map(function(item) {
            return item.id
          })
          return contentDeleteBatch(ids).then(res => {
            if (res.success === 1) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              })
              this.refreshList('onPage')
            }
          })
        })
        .catch(e => e)
    },
    selectionChange(val) {
      this.selectedArry = val
    },
    // 审核按钮
    toExamine() {
      if (this.selectedArry.length === 0) {
        this.$message({
          message: '请选择需要审核的知识',
          type: 'info'
        })
        return
      }
      const isAuditRequired = this.selectedArry[0].isAuditRequired
      const auditor = this.selectedArry[0].auditor
      if (isAuditRequired !== 1) {
        this.$message({
          message: '该知识不需要审核',
          type: 'info'
        })
        return
      }
      if (this.selectedArry[0].state === 2) {
        return this.$message.info('该知识已审核通过')
      }
      if (!this.$isAccount(auditor)) {
        this.$message({
          message: '您没有权限审核该知识',
          type: 'info'
        })
        return
      }
      this.$refs.examine.openDailog(this.selectedArry[0])
    },
    // 刷新列表
    refreshList(type) {
      this.$refs.table.initTableData(type || 'opCondition')
    },
    // 详情事件
    detail(row) {
      this.$router.push({ path: '/knowledgeContentDetail', query: { id: row.id }})
    },
    downloadFile() {
      templateDownload().then(res => {
        if (res.statusText === 'OK') {
          downFileByStream(res.data, '知识内容模板.xlsx')
        }
      })
    }
  }
}
</script>
<style lang='scss' scope>
.knowledgeType .el-upload-list {
  display: none
}
</style>
